{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "e5a770d5",
   "metadata": {},
   "outputs": [],
   "source": [
    "import torchvision \n",
    "from torchvision.models.detection import *\n",
    "from torchvision.io.image import *\n",
    "from torchvision.utils import draw_bounding_boxes\n",
    "from torchvision.transforms.functional import to_pil_image"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "id": "c747dd3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "img = read_image(r'D:\\AI\\datasets\\objectdetection\\640.png',mode = ImageReadMode.RGB)\n",
    "\n",
    "# Step 1: Initialize model with the best available weights\n",
    "\n",
    "weights = FasterRCNN_MobileNet_V3_Large_FPN_Weights.DEFAULT\n",
    "model = torchvision.models.detection.fasterrcnn_mobilenet_v3_large_fpn(weights=weights)\n",
    "model.eval()\n",
    "\n",
    "# Step 2: Initialize the inference transforms\n",
    "preprocess = weights.transforms()\n",
    "\n",
    "\n",
    "# Step 3: Apply inference preprocessing transforms\n",
    "batch = [preprocess(img)]\n",
    "\n",
    "\n",
    "# Step 4: Use the model and visualize the prediction\n",
    "prediction = model(batch)[0]\n",
    "labels = [weights.meta[\"categories\"][i] for i in prediction[\"labels\"]]\n",
    "box = draw_bounding_boxes(img, boxes=prediction[\"boxes\"],\n",
    "                          labels=labels,\n",
    "                          colors=\"red\",\n",
    "                          width=4, font_size=30)\n",
    "im = to_pil_image(box.detach())\n",
    "\n",
    "\n",
    "\n",
    "# im.show()\n",
    "im.save(r'D:\\AI\\datasets\\objectdetection\\a.png')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fcbbd36",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
